//
//  GraphViewController.m
//  AWS Viewer
//
//  Created by Tim Kieboom
//  Copyright (c) 2013 AI&I. All rights reserved.
//


#import "GraphViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPClient.h"
@interface GraphViewController ()

@end

@implementation GraphViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}




- (void)viewDidLoad
{
    [super viewDidLoad];

    hasData = false;
    // We need a hostview, you can create one in IB (and create an outlet) or just do this:
    hostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.frame];
    [hostView setCollapsesLayers:NO];
    [self.view addSubview: hostView];
    
    // Create a CPTGraph object and add to hostView
    graph = [[CPTXYGraph alloc] initWithFrame:hostView.bounds];
    hostView.hostedGraph = graph;
    
    // Get the (default) plotspace from the graph so we can set its x/y ranges
    plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    
    // Note that these CPTPlotRange are defined by START and LENGTH (not START and END) !!
    [plotSpace setYRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat( minYAxis ) length:CPTDecimalFromFloat( lengthYAxis )]];
    [plotSpace setXRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt( -25 ) length:CPTDecimalFromInt( 125 )]];
    
    
    
    axisSet = (CPTXYAxisSet *)graph.axisSet;
    axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromString(@"-1337");
    diff = lengthYAxis / 10.f;
    axisSet.yAxis.majorIntervalLength = [[NSNumber numberWithFloat:diff] decimalValue];
    // Create the plot (we do not define actual x/y values yet, these will be supplied by the datasource...)
    plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero];
    
    // Let's keep it simple and let this class act as datasource (therefore we implement <CPTPlotDataSource>)
    plot.dataSource = self;
    
    // Finally, add the created plot to the default plot space of the CPTGraph object we created before
    [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];

    
    
}

// This method is here because this class also functions as datasource for our graph
// Therefore this class implements the CPTPlotDataSource protocol
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plotnumberOfRecords {
    if(hasData)
        return datapoints.count;
    return 0;
}

// This method is here because this class also functions as datasource for our graph
// Therefore this class implements the CPTPlotDataSource protocol
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    if(hasData)
    {
        NSDictionary *datapoint = datapoints[index];
        
        NSString *value = [datapoint objectForKey:@"value"];
        
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
        
        currentPos++;
        
        if(fieldEnum == CPTScatterPlotFieldX)
        {
            return [NSNumber numberWithLong:currentPos];
        } else {
            return [f numberFromString:value];
        }
    }
    else {
        return [NSNumber numberWithInt:0];
    }
}

-(void) setDataStreamIndex:(int)index
{

    switch (index)
    {
        case DS_AIRPRESSURE_INDEX:
            datastream = @"airpressure";
            minYAxis = 950.f;
            lengthYAxis = 100.f;
            break;
        case DS_HUMIDITY_INDEX:
            datastream = @"hum";
            minYAxis = 40.f;
            lengthYAxis = 70.f;
            break;
        case DS_RAINRATE_INDEX:
            datastream = @"rainrate";
            minYAxis = -1.f;
            lengthYAxis = 50.f;
            break;
        case DS_TEMP_INDEX:
            datastream = @"temp";
            minYAxis = -15.f;
            lengthYAxis = 60.f;
            break;
        case DS_WINDDIR_INDEX:
            datastream = @"winddir";
            minYAxis = 0.f;
            lengthYAxis = 370.f;
            break;
        case DS_WINDSPEED_INDEX:
            datastream = @"windspeed";
            minYAxis = -5.f;
            lengthYAxis = 100.f;
            
            break;
    }
    [self fetchWeekData];
}

-(void)fetchWeekData
{
    

    
    NSUserDefaults *fetchDefaults = [NSUserDefaults standardUserDefaults];
    
    // getting an NSString from userdefaults
    NSString *range = [fetchDefaults objectForKey:@"Range"];
    NSString *interval = [fetchDefaults objectForKey:@"Interval"];
    
   
   if(range == Nil)
   {
       NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
       
       [defaults setObject:@"24hours" forKey:@"Range"];
       [defaults setObject:@"60" forKey:@"Interval"];
       // Synchronizing the defaults. If you don't do this the defaults may or may not sync.
       [defaults synchronize];
       range = [fetchDefaults objectForKey:@"Range"];
       interval = [fetchDefaults objectForKey:@"Interval"];
   }
   
    
   
    //Fetch AWS Data    
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://xively.com/"]];
    NSString *temp = @"https://api.xively.com/v2/feeds/40053/datastreams/";
    
    temp =[temp stringByAppendingString:datastream];
    
    temp =[temp stringByAppendingString: @".json?duration="];
           temp =[temp stringByAppendingString:range];
           temp =[temp stringByAppendingString:@"&interval="];
           temp =[temp stringByAppendingString:interval];
    
          NSLog(@"url = : %@" , temp);
    
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                            path:temp
                                                      parameters:nil];
    
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
    // Set API Key Header
    [request setValue:XIVELY_API_KEY forHTTPHeaderField:@"X-ApiKey"];
    
    
    // Request data
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self operationCompleted:operation byResponse:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self operationFailed:operation withError:error];
    }];
    [operation start];
}

- (void)operationFailed:(AFHTTPRequestOperation *)operation withError:(NSError *)error
{
    NSLog(@"History-Fetch Failed");
}

- (void)operationCompleted:(AFHTTPRequestOperation *)operation byResponse:(id)responseObject
{
    NSLog(@"History-Fetch succeeded");
    // Parse response
    NSData *response = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableContainers error: nil];
    //NSString *titlejson = [json objectForKey:@"id"];
    //graph.title = titlejson;
    datapoints = [json objectForKey:@"datapoints"];

    hasData = true;
    [graph reloadData];

}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
